var attendanceDeviceObj = {};
$(function () {
  page.bind();
  page.getDeptName('1');
  page.getWorkshopName('1');
  page.getPersonName("1");
  page.getPhoneNumber('', '');
  page.getDuty();
  page.getAttendDevice();
  page.removeBtnBind();
  queryPersonnel(myTrim($("#search-text").val()), '1');
  var adddragImgUpload = new DragImgUpload("#add_person_icon", {
    callback: function (files) {
      //回调函数，可以传递给后台等等
      var file = files[0];
      postImgFileToQiniu("fileManager/getQiniuToken", file).then(function (url) {
        $("[name='add_person_img_val']").val(url);
      });
    }
  })
  var updatedragImgUpload = new DragImgUpload("#update_person_icon", {
    callback: function (files) {
      //回调函数，可以传递给后台等等
      var file = files[0];
      postImgFileToQiniu("fileManager/getQiniuToken", file).then(function (url) {
        $("[name='update_person_img_val']").val(url);
      });
    }
  })
});
var phoneNumberArr = [];
var dutyArr = ["1", "2", "3", "跟单", "统计"];
//状态、计薪方式、月薪改前改后
var statusBefore, statusChanged, salaryBefore, salaryChanged;
var effectiveObject; //传递修改对象参数
var page = {
  bind: function () {
    $("#status").bind("change", function () {
      if ($(this).val() === "离职") {
        $("#dismissionTr").show();
      } else {
        $("#dismissionTr").hide();
      }
    });
    //添加人员模态框新增技能
    $("#modalAddSkill").on("click", function () {
      var $tr = $('<tr class="skill"></tr>').append('<td></td>');
      var $td = $('<td></td>').append($(this).siblings().clone(true)).append('&nbsp;<i class="Hui-iconfont Hui-iconfont-del3"></i>');
      $tr.append($td);
      $("#addPersonModal").find("tr.skill:last").after($tr);
      $("#addPersonModal").find("tr.skill:last .skill-name").data("id", "-1").val("");
    });
    //新增技能
    $("#addSkill").on("click", function () {
      var $tr = $('<tr class="skill"></tr>').append('<td></td>');
      var $td = $('<td></td>').append($(this).siblings().clone(true)).append('&nbsp;<i class="Hui-iconfont Hui-iconfont-del3"></i>');
      $tr.append($td);
      $("#table").find("tr.skill:last").after($tr);
      $("#table").find("tr.skill:last .skill-name").data("id", "-1").val("");
    });
    //删除技能
    $("table").on("click", ".Hui-iconfont-del3", function () {
      $(this).parent().parent().remove();
    });
    //点击选择打卡机模态框的确定按钮时
    $("#deviceUserModalBtn").bind("click", function () {
      var data_id = $(this).attr("data-id");
      var element = $('#' + data_id);
      if ($(".right-box li").length <= 0) {
        element.html("<span>请选择</span>");
        element.data('ids', []);
        $("#deviceUserModal").modal("hide");
        return;
      }
      element.html("");
      var ids = [];
      var deviceNameList = [];
      $(".right-box li").each(function () {
        deviceNameList.push($(this).text());
        ids.push($(this).attr("value"));
      });
      element.html("<div style='max-width:380px'>" + deviceNameList.join(' ') + "</div>");
      element.data('ids', ids);
      $("#deviceUserModal").modal("hide");
    });
    //设置考勤机模态框显示
    $("#deviceUserModal").on("show.bs.modal", function () {
      var data_id = $("#deviceUserModalBtn").attr("data-id");
      var element = $('#' + data_id);
      var ids = element.data("ids");
      ids = ids == null ? [] : ids;
      for (var i = 0; i < ids.length; i++) {
        $(".right-box").append($(".left-box").find('[value="' + ids[i] + '"]'));
      }
      page.leftAndRightBind();
    });
    //设置考勤机模态框隐藏
    $("#deviceUserModal").on("hidden.bs.modal", function () {
      $(".left-box").append($(".right-box").find('.item').removeClass('selected-item'));
    });
    $("button[name='openModalBtn']").bind("click", function () {
      $("#deviceUserModalBtn").attr("data-id", $(this).attr("id"));
      $("#deviceUserModal").modal("show");
    });
    //工资相关修改时，生效时间设置“确定”按钮
    $("#confirm").bind("click", function () {
      var arr = effectiveObject["effectiveDateArr"];
      $("#effectiveTimeModal input[name=datePick]").each(function (index) {
        //放入生效日期，当未选择时会默认为当前日期
        arr[index]["effectiveDate"] = $(this).val();
      });
      arr = JSON.stringify(arr);
      effectiveObject["effectiveDateArr"] = arr;
      var personImg = effectiveObject.personImg;
      var imgUrl = $("[name='update_person_img_val']").data('url');
      page.getPersonImgBaseEncode(personImg, imgUrl).then(function (base64Img) {
        effectiveObject = _.cloneDeep(effectiveObject);
        effectiveObject.personImgBaseEncode = base64Img;
        ajaxUtil.ajaxRequest("basicData/updatePerson", effectiveObject).then(function (data) {
          table.ajax.reload(null, false);
          $("#effectiveTimeModal").modal("hide");
          layAlert("修改成功");
          statusBefore = $("#status option:selected").text();
          salaryBefore = $("#monthlySalary").val();

          $("[name='update_person_img_val']").data('url', personImg);
          $("[name='update_person_img_val']").data('base64code', base64Img);
        });
      });
    });
    $("#effectiveTimeModal").on("hide.bs.modal", function () {
      $("#effectiveTimeModalBody").html("");
    });
    $("#status").bind("change", function () {
      statusChanged = $("#status option:selected").text();
    });
    $("#method").bind("change", function () {
      methodChanged = $("#method option:selected").text();
    });
    $("#monthlySalary").bind("change", function () {
      salaryChanged = $("#monthlySalary").val();
    });
    $("#search-text").keyup(function (event) { //搜索框回车事件
      var searchText = myTrim($("#search-text").val());
      setTimeout(function () {
        queryPersonnel(searchText, $("#view").val());
      }, 300);
    });
    $("#search-btn").bind("click", function () {
      queryPersonnel(myTrim($("#search-text").val()), $("#view").val());
    });
    $("#duty").bind("change", function () {
      if ($(this).val() == "自定义") {
        $("#custom").show();
      } else {
        $("#custom").hide();
      }
    });
    $("#modalDuty").bind("change", function () {
      if ($(this).val() == "自定义") {
        $("#modalCustom").show();
      } else {
        $("#modalCustom").hide();
      }
    });
    $("#custom,#modalCustom").bind("blur", function () {
      var value = $(this).val();
      if (value.length > 10) {
        $(this).val("");
        layer.msg("长度过长", {
          icon: "2"
        });
      }
      if (value == "请选择" || value == "自定义") {
        $(this).val("");
        layer.msg("此名称不可使用", {
          icon: "2"
        });
      }
    });
    $("#modalPhoneNumber").bind("blur", function () {
      var value = $(this).val();
      if ($.inArray(value, phoneNumberArr) != -1) {
        layer.msg("该手机号已被使用", {
          'icon': 2
        });
      }
    });
    //点击切换查看状态按钮
    $("#view").bind("click", function () {
      var view = $("#view").val();
      view = view == "1" ? "0" : "1";
      page.getPersonName(view);
      queryPersonnel(myTrim($("#search-text").val()), view);
      $("#view").val(view);
    });
    //模态框点击添加按钮时
    $("#add").bind("click", function () {
      var personName = $("#modalPersonName").val();
      if (personName == "") {
        layAlert("请填写职员名称");
        return false;
      }
      if (personName.length > 30) {
        layAlert("职员名称长度过长！");
        return false;
      }
      var gender = $("#modalGender").val();
      var deptName = $("#modalDeptName").find("option:selected").text();
      if (deptName == "请选择") {
        layAlert("请选择部门名称");
        return false;
      }
      var workshopNameText = $("#modalWorkshopName option:selected").text();
      var workshopName = $("#modalWorkshopName").val();
      var duty = $("#modalDuty option:selected").val();
      if (duty == "自定义") {
        if ($("#modalCustom").val() == '') {
          layAlert("请填写职务");
          return false;
        }
        duty = $("#modalCustom").val();
        switch (duty) {
          case "经理":
            duty = "1";
            break;
          case "主管":
            duty = "2";
            break;
          case "职员":
            duty = "3";
            break;
        }
      }
      if (workshopNameText == "请选择" && duty != "1") {
        layAlert("请选择所属车间");
        return false;
      }
      if (duty == null || duty == "") {
        layAlert("请选择职务");
        return false;
      }
      var IDNumber = $("#modalIDNumber").val();
      if (IDNumber != "" && !(
          /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/
          .test(IDNumber))) {
        layer.msg("身份证长度或格式错误");
        return false;
      }
      var phoneNumber = $("#modalPhoneNumber").val();
      if (!(/^1[3|4|5|6|7|8|9][0-9]\d{4,8}$/.test(phoneNumber))) {
        layer.msg("不是完整的11位手机号或者正确的手机号前七位");
        return false;
      }
      var mailBox = $("#modalMailBox").val();
      if (mailBox != "" && /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(mailBox) == false) {
        layer.msg("邮箱格式不正确");
        return false;
      }
      var weChatNumber = $("#modalWeChatNumber").val();
      var method = $("#modalMethod").val();
      var monthlySalary = $("#modalMonthlySalary").val();
      if (monthlySalary != "" && /^\d+$/.test(monthlySalary) == false) {
        layer.msg("月薪只能是正整数");
        return false;
      }
      var attendDevice = $("#modalAttendDevice").data("ids");
      if (attendDevice === undefined) {
        attendDevice = [];
      }
      var attendanceDeviceObj = window.attendanceDeviceObj;
      var deviceIdList = [],
        deviceTypeList = [],
        deviceNoList = [];
      for (var i = 0; i < attendDevice.length; i++) {
        var id = attendDevice[i];
        var obj = attendanceDeviceObj[id];
        if (obj === undefined) {
          continue;
        }
        deviceIdList.push(id);
        deviceTypeList.push(obj.deviceType);
        deviceNoList.push(obj.deviceId);
      }
      var highestEducation = $("#modalHighestEducation").val(); //最高学历
      var major = $("#modalMajor").val(); //专业
      if (major.length > 25) {
        layAlert("专业名称请控制在25个字符以内");
        return false;
      }
      var englishLevel = $("#modalEnglishLevel").val(); //英语水平
      var skills = [];
      var flag = false;
      $("#addPersonModal table tr.skill").each(function () {
        var name = $(this).find(".skill-name").val();
        var level = $(this).find(".skill-level").val();
        if (name == "" && level < 0) {
          return true;
        } else if (name == "" && level >= 0) {
          /*layAlert("请填写技能名称");
          flag = true;
          return false;*/
        } else if (name != "" && level < 0) {
          layAlert("请选择技能等级");
          flag = true;
          return false;
        }
        var id = $(this).find(".skill-name").data("id");
        skills.push({
          'id': id,
          'name': name,
          'level': level
        });
      });
      if (flag) {
        return false;
      }
      var socialSecurity = $("#modalSocialSecurity").val(); //社保类型
      var hiredate = $("#modalHiredate").val(); //入职日期
      var cancellingDate = $("#modalCancellingDate").val(); //合同截止日期
      var workerNo = $("[name='modelWorkerNo']").val(); //工号
      var personImg = $("[name='add_person_img_val']").val();
      page.getPersonImgBaseEncode(personImg).then(function (base64Img) {
        ajaxUtil.ajaxRuquest("basicData/insertPerson", {
          'deptName': deptName,
          'workshopID': workshopName,
          'personName': personName,
          'gender': gender,
          'method': method,
          'monthlySalary': monthlySalary,
          'IDNumber': IDNumber,
          'phoneNumber': phoneNumber,
          'mailBox': mailBox,
          'weChatNumber': weChatNumber,
          'duty': duty,
          'attendDeviceId': JSON.stringify(deviceIdList),
          'attendDeviceType': JSON.stringify(deviceTypeList),
          'attendDeviceNo': JSON.stringify(deviceNoList),
          'hiredate': hiredate,
          'cancellingDate': cancellingDate,
          'highestEducation': highestEducation,
          'major': major,
          'englishLevel': englishLevel,
          'socialSecurity': socialSecurity,
          'skills': JSON.stringify(skills),
          'workerNo': workerNo,
          'personImg': personImg,
          personImgBaseEncode: base64Img
        }, function (data) {
          if ($("#modalDuty").val() == '自定义') {
            page.getDuty();
          }
          //点击提交按钮后刷新表
          table.ajax.reload(null, false);
          page.getPersonName($("#view").val());
          layAlert("添加成功");
          $("#addPersonModal").modal("hide");
          $("[name='add_person_img_val']").val("");
          $("#add_person_icon").find("img").attr("src", "img/upload.png");
        });
      });
    });
    //改变部门时
    $("#deptName").bind("change", function () {
      var deptId = $("#deptName").val();
      page.getWorkshopName2(deptId);
    });
    //改变模态框部门时
    $("#modalDeptName").bind("change", function () {
      var deptId = $("#modalDeptName").val();
      page.getWorkshopName2(deptId);
    });
    //改变职员名称时
    $("#personName").bind("change", function () {
      var personName = $("#personName").val();
      page.getPersonDetail(personName);
    });
    //点击提交按钮时
    $("#reportBtn").bind("click", function () {
      var object = page.updateParam();
      if (!object) {
        return false;
      }
      var list = [];
      if (salaryChanged != undefined && salaryChanged != null && salaryChanged != salaryBefore) {
        list.push({
          'fieldValue': '月薪',
          'fieldName': 'monthlySalary',
          'previousValue': salaryBefore,
          'modifiedValue': salaryChanged
        });
      }
      if (list.length > 0) {
        for (var i = 0; i < list.length; i++) {
          var fieldName = list[i].fieldName;
          var fieldValue = list[i].fieldValue;
          var previousValue = list[i].previousValue;
          var modifiedValue = list[i].modifiedValue;
          //日期选择控件，最小日期为本月初
          var html = `<tr>
                <td data-value="${fieldName}">${fieldValue}</td>
                <td>${previousValue}</td>
                <td>${modifiedValue}</td>
                <td><input name="datePick" type="text" class="input-text Wdate" style="width:120px;" placeholder="请选择生效日期" 
                  onfocus="WdatePicker({minDate:'%y-%M-01',dateFmt:'yyyy-MM-dd',isShowClear:false,readOnly:true})"/></td> 
                </tr>`
          $("#effectiveTimeModalBody").append(html);
        }
        if (statusChanged != undefined && statusChanged != null && statusBefore != statusChanged) {
          list.push({
            'fieldValue': '状态',
            'fieldName': '状态',
            'previousValue': statusBefore,
            'modifiedValue': statusChanged
          });
        }
        effectiveObject = object;
        effectiveObject["effectiveDateArr"] = list;
        $("#effectiveTimeModal").modal("show");
        return;
      } else {
        if (statusChanged != undefined && statusChanged != null && statusBefore != statusChanged) {
          list.push({
            'fieldValue': '状态',
            'fieldName': '状态',
            'previousValue': statusBefore,
            'modifiedValue': statusChanged
          });
        }
        list = JSON.stringify(list);
        object["effectiveDateArr"] = list;
      }

      var personImg = object.personImg;
      var imgUrl = $("[name='update_person_img_val']").data('url');
      page.getPersonImgBaseEncode(personImg, imgUrl).then(function (base64Img) {
        object.personImgBaseEncode = base64Img;
        ajaxUtil.ajaxRuquest("basicData/updatePerson", object, function (data) {
          if ($("#duty").val() == '自定义') {
            page.getDuty();
          }
          //点击提交按钮后刷新表
          table.ajax.reload(null, false);
          layAlert("修改成功");
          statusBefore = $("#status option:selected").text();
          salaryBefore = $("#monthlySalary").val();

          $("[name='update_person_img_val']").data('url', personImg);
          $("[name='update_person_img_val']").data('base64code', base64Img);
        });
      })
    });
    $("#modalPersonName").unbind("blur");
    $("#modalPersonName").bind("blur", function () {
      var comfirmPersonName = $("#modalPersonName").val();
      if (comfirmPersonName.length > 0) {
        $.Huimodalalert("职员姓名【<span style='color:red;font-size:30px'>" + comfirmPersonName + "</span>】,请确认无误", 2500);
      }
    });
  },
  getPersonImgBaseEncode: function (newUrl, oldUrl) {
    if (newUrl === '') {
      return Promise.resolve('');
    }

    if (oldUrl !== undefined) {
      if (newUrl === oldUrl) {
        var personImgBaseEncode = $("[name='update_person_img_val']").data('base64code');
        if (personImgBaseEncode !== '') {
          return Promise.resolve(personImgBaseEncode);
        }
      }
    }

    return new Promise(function (resole, reject) {
      ajaxUtil.ajaxRuquest("basicData/getBase64EncodeUTF8", {
        picUrl: newUrl
      }, function (data) {
        resole(data);
      }, function (info) {
        reject(info);
      });
    });
  },
  getAttendDevice: function () {
    ajaxUtil.ajaxRequest("dingTalk/getAttendDevice", {}).then(function (data) {
      $(".left-box").html("");
      var attendanceDeviceObj = {};
      for (var i = 0; i < data.length; i++) {
        var obj = data[i];
        var id = obj.id;
        $(".left-box").append("<li class='item ui-sortable-handle' value='" + obj.id + "' >" + obj.deviceName + "</li>");
        attendanceDeviceObj[id] = _.cloneDeep(obj);
      }
      window.attendanceDeviceObj = attendanceDeviceObj;
    });
  },
  getDuty: function () {
    ajaxUtil.ajaxRequest("basicData/getDuty", {}).then(function (data) {
      $("#duty,#modalDuty").html("");
      $("#duty,#modalDuty").append(
        "<option value=''>请选择</option><option value='1'>经理</option><option value='2'>主管</option><option value='3'>职员</option><option value='跟单'>跟单</option><option value='统计'>统计</option>"
      );
      for (var index = 0; index < data.length; index++) {
        var element = data[index];
        if ($.inArray(element, dutyArr) == -1) {
          $("#duty,#modalDuty").append("<option value='" + element + "'>" + element + "</option>");
        }
      }
      $("#duty,#modalDuty").append("<option value='自定义'>自定义</option>");
    });
  },
  getPhoneNumber: function (phoneNumber, id) {
    ajaxUtil.ajaxRequest("basicData/getPhoneNumber", {
      'phoneNumber': phoneNumber,
      'id': id
    }).then(function (data) {
      phoneNumberArr = data;
    });
  },
  //获取部门名称
  getDeptName: function (view) {
    ajaxUtil.ajaxRuquest('basicData/getDeptName', {
      'view': view
    }, function (data) {
      var html = "<option value=''>请选择</option>";
      for (var i = 0; i < data.length; i++) {
        html = html + "<option value='" + data[i].id + "'>" + data[i].deptName + "</option>"
      }
      $("#modalDeptName").append(html);
      $("#deptName").append(html);
    });
  },
  //从车间生产周期表中获取车间名称填入workshopName控件中
  getWorkshopName: function (view) {
    ajaxUtil.ajaxRuquest('basicData/getWorkshopName', {
        "view": view
      },
      function (data) {
        var html = "";
        if (data.length == 0) {
          var html = "<option value=''>无</option>";
        } else {
          var html = "<option value=''>请选择</option>";
          for (var i = 0; i < data.length; i++) {
            html = html + "<option value='" + data[i].id + "'>" + data[i].workshopName + "</option>"
          }
        }
        $("#modalWorkshopName").html("");
        $("#workshopName").html("");
        $("#modalWorkshopName").append(html);
        $("#workshopName").append(html);
      });
  },
  getWorkshopName2: function (deptId) {
    return ajaxUtil.ajaxRequest('basicData/getWorkshopName2', {
      'deptId': deptId,
      'view': '1'
    }).then(function (data) {
      var html = "<option value=''>请选择</option>";
      if (data.length == 0) {
        html = "<option value=''>无</option>";
      } else {
        for (var i = 0; i < data.length; i++) {
          html += "<option value='" + data[i].id + "'>" + data[i].workshopName + "</option>"
        }
      }
      $("#workshopName").html("");
      $("#workshopName").append(html);
      $("#modalWorkshopName").html("");
      $("#modalWorkshopName").append(html);
      return data;
    });
  },
  //获取职员名称
  getPersonName: function (view) {
    ajaxUtil.ajaxRuquest(
      'basicData/getPersonName', {
        'view': view
      },
      function (data) {
        var html = "<option value=''>请选择</option>";
        for (var i = 0; i < data.length; i++) {
          html = html + "<option value='" + data[i].id + "'>" + data[i].personName + "</option>"
        }
        $("#personName").html(""); //清空
        $("#personName").append(html);
      }
    );
  },
  //获取职员详情
  getPersonDetail: function (id) {
    ajaxUtil.ajaxRuquest(
      'basicData/getPersonDetail', {
        'id': id
      },
      function (data) {
        if (data != "") {
          $("#personId").val(data[0].personId);
          $("#workerNo").val(data[0].workerNo);
          $("#deptName").val(data[0].deptName);
          page.getWorkshopName2(data[0].deptName).then(function () {
            $("#workshopName").val(data[0].workshopID);
          });
          $("#duty").val(data[0].duty);
          $("#custom,modalCustom").hide();
          $("#personName").val(data[0].personId);
          $("#gender").val(data[0].gender);
          $("#method").val(data[0].method);
          $("#monthlySalary").val(data[0].monthlySalary);
          salaryBefore = data[0].monthlySalary;
          salaryChanged = data[0].monthlySalary;
          $("#status").val(data[0].status);
          if (data[0].status == "离职") {
            $("#dismissionReason").val(data[0].dismissionReason);
            $("#dismissionDate").val(data[0].dismissionDate);
            $("#dismissionTr").show();
            $("#dismissionDateTr").show();
          } else {
            $("#dismissionReason").val("");
            $("#dismissionDate").val("");
            $("#dismissionTr").hide();
            $("#dismissionDateTr").hide();
          }
          statusBefore = data[0].status;
          statusChanged = data[0].status;
          $("#IDNumber").val(data[0].idnumber);
          $("#phoneNumber").val(data[0].phoneNumber);
          $("#mailBox").val(data[0].mailBox);
          $("#weChatNumber").val(data[0].weChatNumber);
          if (data[0].deviceList.length > 0) {
            var deviceList = data[0].deviceList;
            var ids = [];
            var deviceNameList = [];
            for (var i = 0; i < data[0].deviceList.length; i++) {
              deviceNameList.push(deviceList[i].deviceName);
              ids.push(deviceList[i].deviceId);
            }
            $("#attendDevice").html("<div style='max-width:380px'>" + deviceNameList.join(' ') + "</div>");
            $("#attendDevice").data('ids', ids);
          } else {
            $("#attendDevice").html("<span>请选择</span>");
            $("#attendDevice").data('ids', []);
          }
          //清空技能
          $("#table tr.skill:first .skill-name").data("id", -1);
          $("#table tr.skill:first .skill-name").val("");
          $("#table tr.skill:first .skill-level").val(-1);
          $("#table tr.skill .Hui-iconfont-del3").each(function () {
            $(this).trigger("click");
          });
          //技能赋值
          if (data[0].userSkillList.length > 0) {
            var userSkillList = data[0].userSkillList;
            for (var index in userSkillList) {
              var element = userSkillList[index];
              if (index == 0) {
                $("#table tr.skill:first .skill-name").data("id", element.id);
                $("#table tr.skill:first .skill-name").val(element.name);
                $("#table tr.skill:first .skill-level").val(element.level);
              } else {
                $("#addSkill").trigger("click");
                $("#table tr.skill:last .skill-name").data("id", element.id);
                $("#table tr.skill:last .skill-name").val(element.name);
                $("#table tr.skill:last .skill-level").val(element.level);
              }
            }
          }
          $("#hiredate").val(data[0].hiredate);
          $("#cancellingDate").val(data[0].cancellingDate);
          $("#highestEducation").val(data[0].highestEducation);
          $("#major").val(data[0].major);
          $("#englishLevel").val(data[0].englishLevel);
          $("#socialSecurity").val(data[0].socialSecurity);
          $("#creater").val(data[0].creater);
          $("#creationTime").val(data[0].creationTime);
          $("#lastModifier").val(data[0].lastModifier);
          $("#lastModifyTime").val(data[0].lastModifyTime);
          $("#sort").val(data[0].sort);
          if (data[0].personImg) {
            var personImg = data[0].personImg;
            if (personImg.indexOf('?') === -1) {
              personImg += '?imageMogr/auto-orient';
            } else {
              if (personImg.indexOf('imageMogr/') === -1) {
                personImg += '|imageMogr/auto-orient';
              }
            }
            $("#update_person_icon").find("img").attr("src", personImg);
            $("[name='update_person_img_val']").data('url', data[0].personImg);
          } else {
            $("#update_person_icon").find("img").attr("src", "img/upload.png");
            $("[name='update_person_img_val']").data('url', '');
          }
          $("[name='update_person_img_val']").val(data[0].personImg);

          var personImgBaseEncode = data[0].personImgBaseEncode;
          if (personImgBaseEncode === null) {
            personImgBaseEncode = '';
          }
          $("[name='update_person_img_val']").data('base64code', personImgBaseEncode);
        }
      }
    )
  },
  //update的参数
  updateParam: function () {
    var personId = $("#personId").val();
    var deptName = $("#deptName").find("option:selected").text();

    var deptId = $("#deptName").val();
    var workshopId = $("#workshopName").val();
    var duty = $("#duty").val();
    if (duty == "自定义") {
      duty = $("#custom").val();
      switch (duty) {
        case "经理":
          duty = "1";
          break;
        case "主管":
          duty = "2";
          break;
        case "职员":
          duty = "3";
          break;
      }
    }
    var personName = $("#personName option:selected").text();
    if (personName == "请选择") {
      layAlert("请选择职员");
      return false;
    }
    var gender = $("#gender option:selected").val();
    var status = $("#status option:selected").text();
    if (status == "请选择") {
      layAlert("请选择状态");
      return false;
    }
    var dismissionReason = "";
    if (status === "离职") {
      dismissionReason = $("#dismissionReason").val();
      if (dismissionReason == "") {
        layAlert("请填写离职原因");
        return false;
      }
    }
    var method = $("#method").val();
    var monthlySalary = $("#monthlySalary").val();
    var IDNumber = $("#IDNumber").val();
    var phoneNumber = $("#phoneNumber").val();
    var mailBox = $("#mailBox").val();
    var weChatNumber = $("#weChatNumber").val();
    var attendDevice = $("#attendDevice").data("ids");
    if (attendDevice === undefined) {
      attendDevice = [];
    }

    var attendanceDeviceObj = window.attendanceDeviceObj;
    var deviceIdList = [],
      deviceTypeList = [],
      deviceNoList = [];
    for (var i = 0; i < attendDevice.length; i++) {
      var id = attendDevice[i];
      var obj = attendanceDeviceObj[id];
      if (obj === undefined) {
        continue;
      }
      deviceIdList.push(id);
      deviceTypeList.push(obj.deviceType);
      deviceNoList.push(obj.deviceId);
    }

    var hiredate = $("#hiredate").val(); //入职日期
    var cancellingDate = $("#cancellingDate").val(); //合同截止日期
    var highestEducation = $("#highestEducation").val(); //最高学历
    var major = $("#major").val(); //专业
    var englishLevel = $("#englishLevel").val(); //英语水平
    var socialSecurity = $("#socialSecurity").val(); //社保类型
    var skills = [];

    if (status == "开启") {
      if (gender == "") {
        layAlert("请选择性别");
        return false;
      }
      if (deptName == "请选择") {
        layAlert("请选择部门");
        return false;
      }
      var workshopNameText = $("#workshopName option:selected").text();
      if (workshopNameText == "请选择" && duty != "1") {
        layAlert("请选择所属车间");
        return false;
      }
      if (duty == "自定义") {
        if ($("#custom").val() == '') {
          layAlert("请填写职务");
          return false;
        }
      }
      if (duty == null || duty == "") {
        layAlert("请选择职务");
        return false;
      }
      if (IDNumber != "" &&
        /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/
        .test(IDNumber) == false) {
        layer.msg("身份证长度或格式错误");
        return false;
      }
      if (!/^1[3|4|5|6|7|8|9][0-9]\d{4,8}$/.test(phoneNumber)) {
        layer.msg("不是完整的11位手机号或者正确的手机号前七位");
        return false;
      }
      if (mailBox != "" && /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(mailBox) == false) {
        layer.msg("邮箱格式不正确");
        return false;
      }
      if (method == "请选择") {
        layAlert("请选择工资计算方式");
        return false;
      }
      if (monthlySalary != "" && /^\d+$/.test(monthlySalary) == false) {
        layer.msg("月薪只能是整数");
        return false;
      }
      if (major.length > 25) {
        layAlert("专业名称请控制在25个字符以内");
        return false;
      }
      var flag = false;
      $("#table tr.skill").each(function () {
        var name = $(this).find(".skill-name").val();
        var level = $(this).find(".skill-level").val();
        if (name == "" && level < 0) {
          return true;
        } else if (name == "" && level >= 0) {
          /*layAlert("请填写技能名称");
          flag = true;
          return false;*/
        } else if (name != "" && level < 0) {
          layAlert("请选择技能等级");
          flag = true;
          return false;
        } else if (name.length > 25) {
          layAlert("技能名称不能大于20个字符");
          flag = true;
          return false;
        }
        var id = $(this).find(".skill-name").data("id");
        skills.push({
          'id': id,
          'name': name,
          'level': level
        });
      });
      if (flag) {
        return false;
      }
    }

    var personImg = $("[name='update_person_img_val']").val();
    if (personImg === null || personImg === undefined) {
      personImg = '';
    }
    var sendData = {
      'personId': personId,
      'deptName': deptName,
      'deptId': deptId,
      'workshopID': workshopId,
      'duty': duty,
      'personImg': personImg,
      'personName': personName,
      'gender': gender,
      'status': status,
      'dismissionReason': dismissionReason,
      'method': method,
      'monthlySalary': monthlySalary,
      'IDNumber': IDNumber,
      'phoneNumber': phoneNumber,
      'mailBox': mailBox,
      'weChatNumber': weChatNumber,
      'attendDeviceId': JSON.stringify(deviceIdList),
      'attendDeviceNo': JSON.stringify(deviceNoList),
      'attendDeviceType': JSON.stringify(deviceTypeList),
      'hiredate': hiredate,
      'cancellingDate': cancellingDate,
      'highestEducation': highestEducation,
      'major': major,
      'englishLevel': englishLevel,
      'socialSecurity': socialSecurity,
      'skills': JSON.stringify(skills),
      'workerNo': $("#workerNo").val()
    }
    return sendData;
  },
  leftAndRightBind: function () {
    $(".item").unbind("click");
    $(".left-box .item").unbind("dblclick");
    $(".right-box .item").unbind("dblclick");
    //单击
    $(".item").bind("click", function () {
      $(this).toggleClass("selected-item");
    });
    //左边双击右移
    $(".left-box .item").bind("dblclick", function () {
      $(".right-box").append($(this).removeClass('selected-item'));
      page.leftAndRightBind();
    });
    //右边双击左移
    $(".right-box .item").bind("dblclick", function () {
      $(".left-box").append($(this).removeClass('selected-item'));
      page.leftAndRightBind();
    });
  },
  removeBtnBind: function () {
    $(".add-one").bind("click", function () {
      $(".right-box").append($(".left-box").find('.selected-item').removeClass('selected-item'));
    });
    $(".add-all").bind("click", function () {
      $(".right-box").append($(".left-box").find('.item').removeClass('selected-item'));
    });
    $(".remove-one").bind("click", function () {
      $(".left-box").append($(".right-box").find('.selected-item').removeClass('selected-item'));
    });
    $(".remove-all").bind("click", function () {
      $(".left-box").append($(".right-box").find('.item').removeClass('selected-item'));
    });
  }
}

var tableData = []; //查询全部人员结果
//查询所有人员
var table;

function queryPersonnel(searchText, view) {
  if (searchText != $("#search-text").val()) {
    return;
  }
  $('#queryPersonnelTable tbody').unbind("click");
  table = ajaxUtil.dataTablesAjax("queryPersonnelTable", 10, "basicData/queryPersonnel", {
    'view': view,
    'searchText': searchText
  }, [{
      "data": "personId"
    },
    {
      "data": "workerNo"
    },
    {
      "data": "personName"
    },
    {
      "data": "deptName"
    },
    {
      "data": "workshopID"
    },
    {
      "data": "duty",
      render: function (data) {
        switch (data) {
          case "1":
            return "经理";
            break;
          case "2":
            return "主管";
            break;
          case "3":
            return "职员";
            break;
          default:
            return data;
        }
      }
    },
    {
      "data": "gender"
    },
    {
      "data": "status"
    }
  ]);
  //行点击事件
  $('#queryPersonnelTable tbody').on('click', 'tr', function () {
    var data = table.row(this).data();
    var id = data.personId;
    page.getPersonDetail(id);
  });
}

function getRequestBasePath() {
  var pathName = window.document.location.pathname;
  var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
  return projectName;
}
var ajaxRequestBasePath = getRequestBasePath();

function ajaxRequest(url, data, hasResult, hasAlert) {
  if (data === undefined) {
    data = {};
  }

  if (hasResult === undefined) {
    hasResult = true;
  }
  if (hasAlert === undefined) {
    hasAlert = true;
  }
  return new Promise(function (resole, reject) {
    var $alert;
    if (window.Vue !== undefined) {
      $alert = Vue.prototype.$alert;
    } else {
      $alert = layAlert;
    }
    $.ajax({
      url: ajaxRequestBasePath + '/' + url,
      type: 'POST',
      data: data,
      dataType: 'json',
      timeout: 60 * 1000,
      success: function (res) {
        var result = res.result;
        var data;
        if (!hasResult) {
          if (result === undefined) {
            result = true;
          }
          data = res;
        } else {
          data = res.data;
        }

        if (!result && hasAlert) {
          if ($alert !== undefined) {
            $alert(res.info, '信息', {
              dangerouslyUseHTMLString: true
            });
          }
          reject({
            textStatus: res.info
          });
          return;
        }
        resole(data);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        if ($alert !== undefined && hasAlert) {
          var readyState = XMLHttpRequest.readyState;
          var status = XMLHttpRequest.status;
          var msg;
          if (readyState === 0 && status === 0) {
            msg = '请求超时';
          } else {
            msg = `请求失败：readyState-${readyState},status-${status}`;
          }
          $alert(msg, '信息', {
            dangerouslyUseHTMLString: true
          });
        }
        reject({
          XMLHttpRequest: XMLHttpRequest,
          textStatus: textStatus,
          errorThrown: errorThrown
        });
      }
    });
  });
}

function postImgFileToQiniu(tokenUrl, file, callback, hasWatermark) {
  var baseImgURL = 'https://upload.shinehao.com.cn';
  return new Promise(function (resolve, reject) {
    ajaxRequest(tokenUrl).then(function (token) {
      var name = file.name;
      var key = new Date().valueOf() + `${name}`;
      var observable = qiniu.upload(file, key, token, {
        fname: name,
        params: {}
      }, {
        useCdnDomain: true,
        disableStatisticsReport: true
      });
      observable.subscribe({
        next: function (event) {
          if (callback !== undefined) {
            callback(event.total.percent);
          }
        },
        complete: function (res) {
          var key = res.key;
          var imgUrl = `${baseImgURL}/${key}`;
          if (hasWatermark) {
            waterMarkUrl = qiniu.watermark({
              mode: 2,
              text: key,
              dissolve: 1,
              fontsize: 800,
              font: '仿宋',
              dx: 0,
              dy: 0,
              fill: '#ff0000'
            });
            imgUrl += `?${waterMarkUrl}`;
          }
          resolve(imgUrl);
        },
        error: function (error) {
          reject(error)
        }
      });
    }).catch(function (error) {
      reject(error);
    });
  });
}
